﻿namespace Reader.Utils;

public static class FileHelper
{
    public static async Task<string> SaveFileAsync(IFormFile file, IWebHostEnvironment hostingEnvironment)
    {
        if (file == null || file.Length == 0)
        {
            throw new ArgumentException("File is null or empty", nameof(file));
        }

        // 确保wwwroot/files目录存在
        var wwwRootPath = hostingEnvironment.WebRootPath;
        var filesPath = Path.Combine(wwwRootPath, "files");
        if (!Directory.Exists(filesPath))
        {
            Directory.CreateDirectory(filesPath);
        }

        // 生成唯一的文件名
        var uniqueFileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
        var filePath = Path.Combine(filesPath, uniqueFileName);

        // 保存文件
        using (var stream = new FileStream(filePath, FileMode.Create))
        {
            await file.CopyToAsync(stream);
        }

        // 返回文件的相对路径
        return Path.Combine("/files", uniqueFileName);
    }   
}